package com.alex.zookeeper.crud;

import com.alex.zookeeper.BaseTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建节点方式
 * 1.同步
 * 2.异步
 */
@Slf4j
public class ZKCreate extends BaseTest {

    /**
     * 同步
     */
    @Test
    public void createSyncNode() throws Exception {
        /**
         * 仔细指定ACL
         */
        List<ACL> aclList = new ArrayList<>();
        // scheme：world
        Id worldScheme = new Id("world", "anyone");
        // scheme:ip
        Id ipScheme = new Id("ip", "192.168.1.112");
        // scheme: auth
        Id authScheme = new Id("auth", "alex");
        // scheme: digest
        Id digestScheme = new Id("digest", "alex:yKldgjycHb+cKPqTAAWrGGVFHw0=");


        //添加授权用户
        zooKeeper.addAuthInfo("digest", "alex:123456".getBytes());

        aclList.add(new ACL(ZooDefs.Perms.CREATE, worldScheme));
        aclList.add(new ACL(ZooDefs.Perms.WRITE, worldScheme));

        /**
         * ACL:
         *  OPEN_ACL_UNSAFE: world:anyone:crdwa
         *  READ_ACL_UNSAFE: world:anyone:r
         *  CREATOR_ALL_ACL: ACL为上面指定的authInfo, 拥有所有的权限
         */
        /**
         * CreateMode:
         *  PERSISTENT: 持久化节点
         *  PERSISTENT_SEQUENTIAL：持久化有序节点
         *  EPHEMERAL：临时节点
         *  EPHEMERAL_SEQUENTIAL：临时有序节点
         *  CONTAINER：
         *  PERSISTENT_WITH_TTL:
         *  PERSISTENT_SEQUENTIAL_WITH_TTL:
         */
        zooKeeper.create("/createSync", "createSync".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 异步
     */
    @Test
    public void createAsyncNode() throws Exception {
        zooKeeper.create("/createAsync", "createAsync".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT, new AsyncCallback.Create2Callback() {

                    /**
                     * 异步创建节点回调参数
                     * @param resultCode：0代表执行成功
                     * @param path：节点路径
                     * @param context：上下文
                     * @param name：节点路径
                     * @param stat：该节点信息stat
                     */
                    @Override
                    public void processResult(int resultCode, String path, Object context, String name, Stat stat) {
                        log.info("a1:{}, a2:{}, a3:{}, a4:{}, a5:{}", resultCode, path, context, name, stat);
                    }
                }, "new Object()");
    }
}
